// @title           Setting模块API
// @version         1.0
// @description     This is a sample server celler server.
// @termsOfService  http://swagger.io/terms/

// @contact.name   API Support
// @contact.url    http://www.swagger.io/support
// @contact.email  sage12345678@qq.com

// @license.name  Apache 2.0
// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html

// @host      localhost:8080
// @BasePath  /
// @schemes http https
// @produce      json,html

// @securityDefinitions.basic   BasicAuth

// @securityDefinitions.apikey	AdminKeyAuth
// @in							header
// @name						Authorization
// @description					管理站用Admin-Token, Header: Authorization
// @scope.write Grants write access

// @externalDocs.description  OpenAPI
// @externalDocs.url          https://swagger.io/resources/open-api/
package settingapp

import (
	"gitee.com/captials-team/ubdframe/src/apps"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/services"
	"gitee.com/captials-team/ubdframe/src/infrastructure/caches"
	mysqlDao "gitee.com/captials-team/ubdframe/src/infrastructure/dao/mysql"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/uber_help"
	"go.uber.org/dig"
	"time"
)

type App struct {
	*apps.App

	l         v1log.ILog
	di        *dig.Container
	ApiServer *ApiServer
}

func (app *App) initCaches(conf *configstc.SettingAppConfig) {
	common.ErrPanic(app.di.Provide(func() caches.ItfCache {
		return caches.NewMemoryStore(time.Minute * 10)
	}), uber_help.ErrAlreadyProvided)

	app.l.Info("provide cache success")
}

func (app *App) initDao(conf *configstc.SettingAppConfig) {
	common.ErrPanic(app.di.Provide(func() interfaces.ItfSettingDao {
		settingDao := mysqlDao.NewSettingDao(conf.DBConfig)

		_, err := settingDao.Migrate()
		common.ErrPanic(err)

		app.l.Info("migrate success")

		return settingDao
	}))

	app.l.Info("provide dao success")
}

func (app *App) initService() {
	common.ErrPanic(app.di.Provide(services.NewSettingService, dig.As(new(interfaces.ItfSettingService))))

	app.l.Info("provide service success")
}

func NewApp(di *dig.Container, conf *configstc.SettingAppConfig, logger v1log.ILog) *App {
	app := &App{
		di:  di,
		l:   logger,
		App: apps.NewApp(di, "admin_app"),
	}

	//初始化
	common.ErrPanic(di.Invoke(app.initCaches))
	common.ErrPanic(di.Invoke(app.initDao))
	common.ErrPanic(di.Invoke(app.initService))

	if conf.ApiServer.Enable {
		common.ErrPanic(di.Provide(NewApiServer))
		common.ErrPanic(di.Invoke(func(api *ApiServer) {
			app.WithApiServer(api)
			app.ApiServer = api
		}))
	}

	return app
}
